import request from '@/config/axios'

// CRM线索 VO
export interface LeadsVO {
  id: number // ID
  name: string // 姓名
  phone: string // 手机号
  source: string // 线索来源
  city: string // 城市
  ip: string // ip
  notes: string // 备注
  status: number // 线索状态
  deptId: number // 部门ID
  assignedTo: number // 客户ID
}

// 分配记录 VO
export interface AssignLogVO {
  id: number
  dataId: number
  dataContent: string
  assignType: number // 1=分配给部门 2=分配给员工 3=分配给API客户
  targetId: string
  apiCode: string | null
  createTime: string
}

// CRM线索 API
export const LeadsApi = {
  // 查询CRM线索分页
  getLeadsPage: async (params: any) => {
    return await request.get({ url: `/weiyi/leads/page`, params })
  },

  // 查询CRM线索详情
  getLeads: async (id: number) => {
    return await request.get({ url: `/weiyi/leads/get?id=` + id })
  },

  // 新增CRM线索
  createLeads: async (data: LeadsVO) => {
    return await request.post({ url: `/weiyi/leads/create`, data })
  },

  // 修改CRM线索
  updateLeads: async (data: LeadsVO) => {
    return await request.put({ url: `/weiyi/leads/update`, data })
  },

  // 删除CRM线索
  deleteLeads: async (id: number) => {
    return await request.delete({ url: `/weiyi/leads/delete?id=` + id })
  },

  // 导出CRM线索 Excel
  exportLeads: async (params) => {
    return await request.download({ url: `/weiyi/leads/export-excel`, params })
  },

  // 自动分配线索
  autoAssignLeads: () => {
    return request.post({ 
      url: '/weiyi/leads/auto-assign'
    })
  },

  // 修改自动分配线索接口
  assignLeads: (force: boolean = false) => {
    return request.post<{
      count: number  // 返回分配的数量
    }>({ 
      url: '/weiyi/leads/assign',
      data: { force }
    })
  },

  // 获取导入模板
  getImportTemplate: () => {
    return request.download({ url: '/weiyi/leads/get-import-template' })
  },

  // 导入线索
  importLeads: (file: File) => {
    const formData = new FormData()
    formData.append('file', file)
    return request.upload({
      url: '/weiyi/leads/import',
      data: formData
    })
  },

  // 分配到部门
  assignToDept: (data: {
    dataIds: number[]
    deptIds: number[]
  }) => {
    return request.post({ 
      url: '/weiyi/data/assign/dept',
      data
    })
  },

  // 分配到员工
  assignToUser: (data: {
    dataIds: number[]
    userIds: number[]
  }) => {
    return request.post({ 
      url: '/weiyi/data/assign/user',
      data
    })
  },

  // 分配到API客户
  assignToApi: (data: {
    dataIds: number[]
    apiClient: string
  }) => {
    return request.post({ 
      url: '/weiyi/data/assign/api',
      data
    })
  },

  // 获取分配记录
  getAssignLogs: (dataId: number) => {
    return request.get<AssignLogVO[]>({ 
      url: '/weiyi/leads/assign-logs',
      params: { dataId }
    })
  },

  // 批量查询线索分配记录状态
  batchCheckAssignLogs: (ids: number[]) => {
    return request.post<any>({ url: '/weiyi/leads/batch-check-assign-logs', data: { ids } })
  }
}